package com.jzoffer;

import java.util.ArrayDeque;
import java.util.Queue;

/*
* 输入一棵二叉树，求该树的深度。
* 从根结点到叶结点依次经过的结点（含根、叶结点）
* 形成树的一条路径，最长路径的长度为树的深度。
* */
public class TheDepthOfRoot {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new TreeNode(3);
        TreeNode t4 = new TreeNode(4);
        TreeNode t5 = new TreeNode(5);
        t1.left = t2;
        t1.right = t3;
        t2.left = t4;
        t4.right = t5;
        System.out.println(treeDepth(t1));
        System.out.println(treeDepth2(t1));
    }

    public static int treeDepth(TreeNode root){
        if(root == null){
            return 0;
        }
        int leftHeight = treeDepth(root.left);
        int rightHeight = treeDepth(root.right);
        return 1 + Math.max(leftHeight,rightHeight);
    }

    public static int treeDepth2(TreeNode root){
        if(root == null){
            return 0;
        }
        // 使用层序遍历
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        int floor = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0;i < size;i++){
                TreeNode t = queue.poll();
                if(t.left != null){
                    queue.offer(t.left);
                }
                if(t.right != null){
                    queue.offer(t.right);
                }
            }
            floor++;
        }
        return floor;
    }
}
